package com.bzqn.baseframe;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.bzqn.baseframe.BaseTabar.OnTabBarChangeListener;

@SuppressLint("InlinedApi")
public class BZQNFrameActivity extends BaseActivity implements ViewUnitContent,
		OnTabBarChangeListener {
	
	public static final String CONFIG_FILENAME = "config.json";
	private RootRelativelayoutView mRootView;
	private BaseNavicationBar mNavicationHeader;
	private BaseTabar mBaseTabar;
	private Config mConfig;
	private CustomViewPager mNavicationPager;
	private RelativeLayout mContentView;
	private DrawerLayout mDrawerLayout;
	private int mCurrentTabIndex = 0;
	

	/**
	 * 决定是否添加选项卡的ViewPager默认为true,如果不添加ViewPager,选项卡将变得没有任何意义
	 * @return
	 */
	@Deprecated
	protected boolean addNavicationPager() {
		return true;
	}
	/**
	 * 设置ViewPager是否可以滑动切换，这个方法如果在侧滑状态下会产生事件冲突问题，待解决.
	 * @return
	 */
	@Deprecated
	protected void setNavicationCanScroll(boolean scroll) {
		getNavicationPager().setScanScroll(scroll);
	}

	/**
	 * 代替setContentView,这个View将被设置到默认的显示区域，在导航标题的下面
	 * @param view
	 */
	protected void setTitleModeContentView(View view) {
		if (view != null) {
			RelativeLayout.LayoutParams rootViewParams = new LayoutParams(
					MATCH_PARENT, MATCH_PARENT);
			mContentView.addView(view, rootViewParams);
		}
	}
	/**
	 * 代替setContentView,这个View将被设置到默认的显示区域，在导航标题的下面
	 * @param view
	 */
	protected void setTitleModeContentView(View view, ViewGroup.LayoutParams params) {
		if (view != null && params != null) {
			mContentView.addView(view, params);
		}
	}
	/**
	 * 代替setContentView,这个View将被设置到默认的显示区域，在导航标题的下面
	 * @param view
	 */
	protected void setTitleModeContentView(int layoutResId) {
		if (layoutResId != 0) {
			View v = getLayoutInflater().inflate(layoutResId, null);
			RelativeLayout.LayoutParams rootViewParams = new LayoutParams(
					MATCH_PARENT, MATCH_PARENT);
			mContentView.addView(v, rootViewParams);
		}
	}

	/**
	 * 决定是否添加侧滑
	 * @return
	 */
	protected boolean initDrawerLayout() {
		return true;
	}
	/**
	 * 初始化左侧侧滑的内容 侧滑的内容的布局必须指定android:layout_gravity="start"
	 * @return
	 */
	protected View initDrawerLayoutLeftContent() {
//		DrawerLayout.LayoutParams leftParams = new DrawerLayout.LayoutParams(MATCH_PARENT,MATCH_PARENT);
//		leftParams.gravity = Gravity.START;
//		LinearLayout left = new LinearLayout(this);
//		left.setLayoutParams(leftParams);
//		left.setBackgroundColor(Color.YELLOW);
		return null;
	}
	/**
	 * 初始化右侧侧滑的内容 侧滑的内容的布局必须指定android:layout_gravity="end"
	 * @return
	 */
	protected View initDrawerLayoutRightContent() {
//		DrawerLayout.LayoutParams rightParams = new DrawerLayout.LayoutParams(MATCH_PARENT,MATCH_PARENT);
//		rightParams.gravity = Gravity.END;
//		LinearLayout right = new LinearLayout(this);
//		right.setLayoutParams(rightParams);
//		right.setBackgroundColor(Color.YELLOW);
		return null;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 加载本地GSON文件
		File local = new File(getCacheDir(), CONFIG_FILENAME);
		if (!local.exists()) {
			try {
				String json = Utils.convertStreamToString(getAssets().open(
						CONFIG_FILENAME));
				if (json.endsWith("/n")) {
					json = new StringBuffer(json).delete(
							json.lastIndexOf("/n"), json.length()).toString();
				}
//				mConfig = new Gson().fromJson(json, Config.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			// 读取cache下的对象
			try {
				InputStream in = new FileInputStream(new File(getCacheDir(),
						CONFIG_FILENAME));
				String cacheJson = Utils.convertStreamToString(in);
				if (cacheJson.endsWith("/n")) {
					cacheJson = new StringBuffer(cacheJson).delete(
							cacheJson.lastIndexOf("/n"), cacheJson.length())
							.toString();
				}
//				mConfig = new Gson().fromJson(cacheJson, Config.class);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

		}
		if (mConfig == null) {
			mConfig = new Config();
			mConfig.setNavigationBarConfig(new NavigationBarConfig());
			mConfig.setTabBarConfig(new TabBarConfig());
		}
		List<TabButtonConfig> buttons = initTabButtons();
		mConfig.getTabBarConfig().setButtons(buttons);
		mRootView = new RootRelativelayoutView(this);
		mDrawerLayout = new DrawerLayout(this);
		RelativeLayout.LayoutParams rootViewParams = new LayoutParams(
				MATCH_PARENT, MATCH_PARENT);
		mDrawerLayout.addView(mRootView, rootViewParams);

		mRootView.setBackgroundColor(Color.WHITE);
		mNavicationHeader = initNavicationView();
		setmNavicationPager(new CustomViewPager(this));
		if(buttons != null){
			getNavicationPager().setOffscreenPageLimit(buttons.size());
		}
		setNavicationCanScroll(false);
		mBaseTabar = initTabBarView();
		mBaseTabar.addToRelativeLayoutParent(mRootView, this);
		mNavicationHeader.addToRelativeLayoutParent(mRootView, this);

		RelativeLayout.LayoutParams contentViewParams = new LayoutParams(
				MATCH_PARENT, MATCH_PARENT);
		contentViewParams.topMargin = Utils.dip2px(mConfig
				.getNavigationBarConfig().getNavigationHeight(), this);
		contentViewParams.bottomMargin = Utils.dip2px(mConfig
				.getNavigationBarConfig().getNavigationHeight(), this);
		mContentView = new RelativeLayout(this);
		mContentView.setBackgroundColor(Color.LTGRAY);
		mRootView.addView(mContentView, contentViewParams);
		if (addNavicationPager()) {
			RelativeLayout.LayoutParams params = new LayoutParams(MATCH_PARENT,
					MATCH_PARENT);
			mContentView.addView(getNavicationPager(), params);
			if (buttons != null && buttons.size() != 0) {
				// setAdapter
				MyViewPagerAdapter mAdapter = new MyViewPagerAdapter(buttons);
				getNavicationPager().setAdapter(mAdapter);
				// 添加DrawerLayout
				if(initDrawerLayout()){
					//是否添加侧滑抽屉
					View vLeft = initDrawerLayoutLeftContent();
					View vRight = initDrawerLayoutRightContent();
					if(vLeft != null && vRight != null){
						mDrawerLayout.addView(vLeft);
						mDrawerLayout.addView(vRight);
					} else if(vLeft != null){
						mDrawerLayout.addView(vLeft); 
					} else if(vRight != null){
						mDrawerLayout.addView(vRight);
					}
				}
			}
		}
		
		setContentView(mDrawerLayout, rootViewParams);
		mDrawerLayout.setDrawerListener(new DrawerListener() {
			
			@Override
			public void onDrawerStateChanged(int state) {
				
			}
			
			@Override
			public void onDrawerSlide(View view, float slide) {
				BZQNFrameActivity.this.onDrawerSlide(view, slide);
			}
			
			@Override
			public void onDrawerOpened(View view) {
				BZQNFrameActivity.this.onDrawerOpened(view);
			}
			
			@Override
			public void onDrawerClosed(View view) {
				BZQNFrameActivity.this.onDrawerClosed(view);
			}
		});
	}

	protected void onDrawerSlide(View view , float slide) {
		
	}
	protected void onDrawerClosed(View view) {
		
	}
	protected void onDrawerOpened(View view) {
		
	}
	/**
	 * 导航左侧按钮的点击事件
	 * @param listener
	 */
	protected void setNavicationLeftButtonClickListener(OnClickListener listener) {
		mNavicationHeader.setLeftButtonOnClickListener(listener);
	}

	/**
	 * 导航右侧按钮的点击事件
	 * @param listener
	 */
	protected void setNavicationRightButtonClickListener(
			OnClickListener listener) {
		mNavicationHeader.setRightButtonOnClickListener(listener);
	}

	/**
	 * 是否隐藏选项卡中的内容,选项卡的内容被隐藏的话，选项卡存在将没有任何意义
	 * @param hidden
	 */
	@Deprecated
	protected void setNavicationPagerHidden(boolean hidden) {
		getNavicationPager().setVisibility(hidden == true ? View.GONE
				: View.VISIBLE);
	}

	protected void setContentViewBackgroundColor(int color) {
		mContentView.setBackgroundColor(color);
	}

	protected void setRootViewBackgroundColor(int color) {
		mRootView.setBackgroundColor(color);
	}

	protected void setNavicationLeftButtonHidden(boolean hidden) {
		mNavicationHeader.setVisibility(hidden == true ? View.GONE
				: View.VISIBLE);
	}

	protected void setNavicationRightButtonHidden(boolean hidden) {
		mNavicationHeader.getRightButton().setVisibility(
				hidden == true ? View.GONE : View.VISIBLE);
	}

	/**
	 * 是否隐藏导航标题栏
	 * @param hidden
	 * @param animation
	 */
	protected void setNavicationBarHidden(boolean hidden, Animation animation) {
		mNavicationHeader.getLeftButton().setVisibility(
				hidden == true ? View.GONE : View.VISIBLE);
		if (animation != null) {
			mNavicationHeader.startAnimation(animation);
		}
		RelativeLayout.LayoutParams params = (LayoutParams) mContentView
				.getLayoutParams();
		if (params != null) {
			params.topMargin = hidden == true ? 0 : Utils.dip2px(mConfig
					.getNavigationBarConfig().getNavigationHeight(), this);
			mContentView.setLayoutParams(params);
		}

	}

	/**
	 * 是否隐藏TabBar
	 * @param hidden
	 * @param animation
	 */
	protected void setTabBarHidden(boolean hidden, Animation animation) {
		mBaseTabar.setVisibility(hidden == true ? View.GONE : View.VISIBLE);
		if (animation != null) {
			mBaseTabar.startAnimation(animation);
		}
		RelativeLayout.LayoutParams params = (LayoutParams) mContentView
				.getLayoutParams();
		if (params != null) {
			params.bottomMargin = hidden == true ? 0 : Utils.dip2px(mConfig
					.getTabBarConfig().getTabBarHeight(), this);
			mContentView.setLayoutParams(params);
		}
	}

	protected void setNavicationTitle(String title) {
		getNavicationHeader().getTitleView().setText(title);
	}

	protected void setNavicationTitleBackgroundColor(int colod) {
		getNavicationHeader().getTitleView().setBackgroundResource(colod);
	}

	protected void setNavicationTitleTextSize(int spSize) {
		getNavicationHeader().getTitleView().setTextSize(
				TypedValue.COMPLEX_UNIT_SP, spSize);
	}







	/**
	 * 重新设定TabBar的内容，这个集合应该在初始化的时候后已经是定好
	 * @param buttons
	 */
	@Deprecated
	protected void setTabBarButtons(List<TabButtonConfig> buttons) {
		getTabar().getmTabBarConfig().setButtons(buttons);
		getTabar().resetView(this);
	}

	@Override
	void onHttpRet(String content) {
		super.onHttpRet(content);
		Log.i("RET", content);
	}

	public RelativeLayout getRootView() {
		return mRootView;
	}

	public BaseNavicationBar getNavicationHeader() {
		return mNavicationHeader;
	}

	public BaseTabar getTabar() {
		return mBaseTabar;
	}

	protected List<TabButtonConfig> initTabButtons() {
		return null;
	}

	public RelativeLayout getContentView() {
		return mContentView;
	}

	/**
	 * 通过TabBarConfig 来初始化一个TabBar
	 * @return
	 */
	protected BaseTabar initTabBarView() {
		return new BaseTabar(this, mConfig == null ? null
				: mConfig.getTabBarConfig(), this);
	}

	/**
	 * 通过NavigationBarConfig 来初始化一个NavicationBar
	 * @return
	 */
	protected BaseNavicationBar initNavicationView() {
		return new BaseNavicationBar(this, mConfig == null ? null
				: mConfig.getNavigationBarConfig());
	}

	/**
	 * 选项卡切换的监听事件，重写这个方法时如果不带super选项卡将不会自动切换标题
	 */
	@Override
	public void onTabBarChange(int index) {
		getNavicationPager().setCurrentItem(index, false);
		setmCurrentTabIndex(index);
		//发送事件
		BZQNFrameEventSingleInstance.getInstance().sendTabChangeEvent(index);
		if (mConfig.getTabBarConfig().getButtons() != null
				&& mConfig.getTabBarConfig().getButtons().size() != 0) {
			if (TextUtils.isEmpty(mConfig.getTabBarConfig().getButtons()
					.get(index).getTitleViewText())) {
				setNavicationTitle(mConfig.getTabBarConfig().getButtons()
						.get(index).getTabButtonText());
			} else {
				setNavicationTitle(mConfig.getTabBarConfig().getButtons()
						.get(index).getTitleViewText());
			}
		}
	}
	public int getCurrentTabIndex() {
		return mCurrentTabIndex;
	}
	public void setmCurrentTabIndex(int mCurrentTabIndex) {
		this.mCurrentTabIndex = mCurrentTabIndex;
	}
	public CustomViewPager getNavicationPager() {
		return mNavicationPager;
	}
	public void setmNavicationPager(CustomViewPager mNavicationPager) {
		this.mNavicationPager = mNavicationPager;
	}

}
